import fs from 'fs';
import path from 'path';
import jwt from 'jsonwebtoken';
import { jwtSecretMd5 } from '../config';
import { conn } from '../model/db';
import mm from 'music-metadata';
import dayjs from 'dayjs';

export const deleteFolderRecursive = (folderPath) => { // 递归删除文件夹
  if (fs.existsSync(folderPath)) {
    fs.readdirSync(folderPath).forEach((file) => {
      const curPath = path.join(folderPath, file);
      if (fs.lstatSync(curPath).isDirectory()) {
        deleteFolderRecursive(curPath); // 递归删除子文件夹
      } else {
        fs.unlinkSync(curPath); // 删除文件
      }
    });
    fs.rmdirSync(folderPath); // 删除空文件夹
  }
};

export const fileFormat = (name: string) => { // 获取文件后缀名匹配格式
  // 获取最后一个点的索引
  const lastDotIndex = name.lastIndexOf('.');
  // 提取最后一个点之后的部分作为后缀名
  const extension = name.substr(lastDotIndex + 1).toLowerCase();
  return getContentType(extension);

  function getContentType (imageType) {
    switch (imageType.toLowerCase()) {
      case 'jpg':
      case 'jpeg':
        return 'image/jpeg';
      case 'png':
        return 'image/png';
      case 'gif':
        return 'image/gif';
      case 'bmp':
        return 'image/bmp';
      case 'webp':
        return 'image/webp';
      case 'svg':
        return 'image/svg+xml';
      case 'mp4':
        return 'video/mp4';
      case 'webm':
        return 'video/webm';
      case 'mov':
        return 'video/quicktime';
      case 'avi':
        return 'video/x-msvideo';
      case 'wmv':
        return 'video/x-ms-wmv';
      case 'mp3':
        return 'audio/mpeg';
      case 'wav':
        return 'audio/wav';
      case 'ogg':
        return 'audio/ogg';
      case 'm4a':
        return 'audio/mp4';
      case 'txt':
        return 'text/plain';
      case 'html':
        return 'text/html';
      case 'css':
        return 'text/css';
      case 'csv':
        return 'text/csv';
      case 'xml':
        return 'application/xml';
      case 'json':
        return 'application/json';
      case 'pdf':
        return 'application/pdf';
      case 'doc':
      case 'docx':
        return 'application/msword';
      case 'xls':
      case 'xlsx':
        return 'application/vnd.ms-excel';
      case 'ppt':
      case 'pptx':
        return 'application/vnd.ms-powerpoint';
      case 'zip':
        return 'application/zip';
      case 'rar':
        return 'application/x-rar-compressed';
      case 'tar':
        return 'application/x-tar';
      case 'gz':
        return 'application/gzip';
      case 'dwg':
        return 'application/acad';
      case 'dxf':
        return 'application/dxf';
      case '':
      case 'ts':
      case 'js':
      case 'less':
      case 'scss':
      case 'vue':
        return 'application/javascript';
      default:
        return 'application/octet-stream';
    }
  }
};

export const changePermissionsRecursive = (dirPath, mode) => { // 递归修改文件权限
  const files = fs.readdirSync(dirPath);
  files.forEach(file => {
    const filePath = path.join(dirPath, file);
    const stats = fs.statSync(filePath);
    if (stats.isDirectory()) { // 如果是目录，则递归调用自身
      changePermissionsRecursive(filePath, mode);
    } else { // 如果是文件，则修改权限
      fs.chmodSync(filePath, mode);
    }
  });
};

export const replaceSpecialCharacters = (str: string) => { // 匹配特殊字符的正则表达式
  let result = str.replace(/\.[^.]*$/, ''); // 去掉最后小数点后面的字符
  const regex = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g;
  result = result.replace(regex, '');
  return result;
};

export const removeSubstring = (str: string, substring: string) => { // 删除字符串中指定的子字符串
  const parts = str.split(substring);
  return parts.join('');
};

export const firstTimeCreationUser = async (user = 'sysadmin') => { // 第一次创建的管理用户
  const selectQuery = `SELECT * FROM users WHERE [user]='${user}'`;
  try {
    const isUser = await selectQueryFunc(selectQuery);
    if (!isUser.data) {
      const insertQuery = `
        INSERT INTO users ([user], pass, jurisdiction, createTime, photo, name, sex, age)
          VALUES (
            '${user}',
            'rongmu',
            2,
            '${dayjs().format('YYYY-MM-DD HH:mm:ss')}',
            'https://q.qlogo.cn/headimg_dl?dst_uin=2682073669&spec=640',
            '超级管理员',
            1,
            25
          )
      `;
      await selectQueryFunc(insertQuery, (insertErr, insertResults) => {
        if (insertErr) {
          formatReqLog(500, '超级管理员数据初始化新增失败', insertErr, { user: 'system' });
        } else {
          formatReqLog(200, '超级管理员数据初始化新增成功', insertResults, { user: 'system' });
        }
      });
    }
  } catch (err) {
    formatReqLog(501, '超级管理员数据初始化新增失败', err, { user: 'system' });
  }
};

// 保存日志
export const formatReqLog = (code: number, msg: string, obj: any, more?: any) => { // 保存日志
  // const insertQuery = `
  //   INSERT INTO logs (code, msg, [info], [more], [user], path, createTime)
  //     VALUES (
  //       ${code},
  //       '${msg}',
  //       '[${JSON.stringify(obj)}]',
  //       '[${JSON.stringify(more)}]',
  //       '[${(more.user || '-')}]',
  //       '${(more.path || '-')}',
  //       '${dayjs().format('YYYY-MM-DD HH:mm:ss')}'
  //     )
  // `;
  // if (more.user) {
    // conn.query(insertQuery);
  //   console.log(code, msg, obj, more, dayjs().format('YYYY-MM-DD HH:mm:ss'));
  // }
  return {
    code,
    msg,
    data: obj,
    ...more,
    user: undefined,
    sql: undefined
  };
};

export const mkdirs = (dirPath: string) => { // 目录不存在即创建目录
  if (!fs.existsSync(dirPath)) fs.mkdirSync(dirPath, { recursive: true });
};

export const selectQueryFunc = async (SELECT: string, callback?: any) => {
  const res = { err: null as any, data: null as any } as any;
  try {
    return await new Promise((resolve, reject) => {
      conn.query(SELECT, (insertErr, insertResults) => {
        if (insertErr) {
          reject(insertErr);
        } else {
          const obj = insertResults.recordset ? insertResults.recordset : [];
          resolve({
            data: obj.length === 1 ? obj[0] : (obj.length > 0 ? obj : null)
          });
        }
        if (callback) callback(insertErr, insertResults);
      });
    });
  } catch (err) {
    res.err = err;
    return res;
  }
};

export const verifyAuthentication = async (key = '') => { // 验证token
  const token = key.replace('Bearer ', '');
  let data = {};
  try {
    const result = jwt.verify(token, jwtSecretMd5) as any;
    data = await selectQueryFunc(`SELECT * FROM users WHERE id='${result.id}'`);
  } catch (err) {
    data = { err };
  }
  return data;
};

export const getStringBetweenChars = (str: string, startStr: string, endStr: string) => { // 获取字符串中指定的子字符串
  let startIndex = str.indexOf(startStr);
  if (startIndex === -1) return ''; // 如果找不到起始字符串，则返回空字符串
  startIndex += startStr.length;
  const endIndex = str.indexOf(endStr, startIndex);
  if (endIndex === -1) return ''; // 如果找不到结束字符串，则返回空字符串
  return str.substring(startIndex, endIndex);
};

export const getAudioDuration = async (filePath: string) => {
  return new Promise((resolve) => {
    fs.readFile(filePath, async (err, data) => {
      if (!err && data) { // 使用 music-metadata 模块解析文件元数据
        try {
          const metadata = await mm.parseFile(filePath);
          if (metadata && metadata.format && metadata.format.duration) {
            resolve(metadata.format.duration);
          } else {
            console.error('Failed to get duration from metadata');
            resolve(0);
          }
        } catch (error) {
          console.error('Error parsing metadata:', error.message);
          resolve(0);
        }
      }
    });
  });
};
